const fork = require("child_process").fork;
const cpus = require("os").cpus();

const server = require("net").createServer();
server.listen(3000);
process.title = "node-master";

const workers = {};
const createWorker = () => {
  const worker = fork("./worker.js");
  worker.on("message", function (message) {
    if (message.act === "zidingyide") {
      createWorker();
    }
  });
  worker.on("exit", function (code, signal) {
    console.log("worker 子进程退出code: " + code + ", signal: " + signal);
    delete workers[worker.pid];
  });
  worker.send("server", server);
  workers[worker.pid] = worker;
  console.log(
    "worker 子进程创建 pid： " + worker.pid + " ,ppid: " + process.ppid
  );
};

for (let i = 0; i < cpus.length; i++) {
  createWorker();
}

process.once("SIGINT", close.bind(this, "SIGINT"));
process.once("SIGQUIT", close.bind(this, "SIGQUIT"));
process.once("SIGTERM", close.bind(this, "SIGTERM"));
process.once("exit", close.bind(this));

function close(code) {
  console.log("退出进程！code：" + code);
  if (code !== 0) {
    for (let pid in workers) {
      console.log("master process exit, kill worker " + pid);
      workers[pid].kill("SIGINT");
    }
  }
  process.exit(0);
}
